using System;
using LitJson2;
using UnityEngine;

/****************************************************
// 功能：移动设备相关操作管理器
// | Talk To [ 聊来改善地区金融服务环境，助力企业发展 ]
// | Copyright (c) 2021-2025 聊来 All rights reserved.
// | Licensed ( <a href="http://www.apache.org/licenses/LICENSE-2.0">聊来</a> )
// | @Author: 贯彻己道的云 <18970881148@qq.com>
// | DateTime: 2025/1/8 15:24:34
*****************************************************/

public class PhoneController : SingletonPatternBase<PhoneController>
{
    public bool isLogin { get; set; } = false;

    public PlatformEnum currentPlatform = PlatformEnum.None;
    
    public Action<PlatformEnum> loginSuccess; 
    public Action<PlatformEnum> loginFail;
    public Action<PlatformEnum> loginCancel;

    public void AutoLogin()
    {
#if !UNITY_EDITOR
        if (PlayerPrefs.HasKey("Login"))
        {
            PlatformEnum platform = (PlatformEnum) Enum.Parse(typeof(PlatformEnum), PlayerPrefs.GetString("Login"));
            if (platform == PlatformEnum.QQ)
            {
                if (QQCheckSessionValid())
                {
                    JsonData jd = RefreshQQSession();
                    LoginCallBack(jd, PlatformEnum.QQ);
                }
            }
            else if (platform == PlatformEnum.WX)
            {
                if (WxCheckSessionValid())
                {
                    JsonData jd = RefreshWxSession();
                    LoginCallBack(jd, PlatformEnum.WX);
                }
            }
        }
        else
        {
            if (QQCheckSessionValid())
            {
                JsonData jsonData = RefreshQQSession();
                LoginCallBack(jsonData, PlatformEnum.QQ);
            }
            else if (WxCheckSessionValid())
            {
                JsonData jsonData = RefreshWxSession();
                LoginCallBack(jsonData, PlatformEnum.WX);
            } 
        }
#endif

    }
    
    /// <summary>
    /// 登录
    /// </summary>
    /// <param name="platform"></param>
    public void Login(PlatformEnum platform)
    {
        switch (platform)
        {
            case PlatformEnum.None:
                LoginController.Instance.ClickYouKe();
                break;
            case PlatformEnum.QQ:
                PlatformMsgManager.Instance.SendUnityMessageToPlatform(Constants.PLATFORM_MSG_QQ_LOGIN);
                break;
            case PlatformEnum.WX:
                PlatformMsgManager.Instance.SendUnityMessageToPlatform(Constants.PLATFORM_MSG_WX_LOGIN);
                break;
        }
    }

    /// <summary>
    /// 退出登录
    /// </summary>
    public void Logout()
    {
        switch (currentPlatform)
        {
            case PlatformEnum.None:
                Debug.Log("游客退出登录");
                break;
            case PlatformEnum.QQ:
                PlatformMsgManager.Instance.SendUnityMessageToPlatform(Constants.PLATFORM_MSG_QQ_LOGOUT);
                break;
            case PlatformEnum.WX:
                PlatformMsgManager.Instance.SendUnityMessageToPlatform(Constants.PLATFORM_MSG_WX_LOGOUT);
                break;
        }
    }
    
    
    /// <summary>
    /// 登录回调
    /// </summary>
    /// <param name="jsonData">返回的数据</param>
    /// <param name="platform">平台类型</param>
    /// <param name="result">登录结果 0 == 成功 1 == 失败 2 == 取消</param>
    public void LoginCallBack(JsonData jsonData, PlatformEnum platform, int result = 0)
    {
        switch (result)
        {
            case 0:
                Debug.Log("票据获取：" + jsonData.ToJson());
                string openId = (string) jsonData["openid"];
                string unionid = (string) jsonData["unionid"];
                string token = (string) jsonData["token"];
                isLogin = true;
                currentPlatform = platform;
                loginSuccess?.Invoke(platform);
                PlayerPrefs.SetString("Login", platform.ToString());
                PlayerPrefs.Save();
                break;
            case 1:
                loginFail?.Invoke(platform);
                break;
            case 2:
                loginCancel?.Invoke(platform);
                break;
        }
    }
    
    /// <summary>
    /// QQ授权是否有效
    /// </summary>
    /// <returns></returns>
    private bool QQCheckSessionValid()
    {
        var str = PlatformMsgManager.Instance.GetStringFormPlatform(Constants.UNITY_GET_STRING_QQ_AUTORVAILD);
        return Convert.ToBoolean(str != string.Empty ? str : false);
    }

    /// <summary>
    /// 刷新获取票据
    /// </summary>
    /// <returns></returns>
    private JsonData RefreshQQSession()
    {
        var jsonData = JsonMapper.ToObject(PlatformMsgManager.Instance.GetStringFormPlatform(Constants.UNITY_GET_STRING_QQ_REFRESHSESSION));

        return jsonData;
    }
    
    /// <summary>
    /// QQ授权是否有效
    /// </summary>
    /// <returns></returns>
    private bool WxCheckSessionValid()
    {
        var str = PlatformMsgManager.Instance.GetStringFormPlatform(Constants.UNITY_GET_STRING_WX_AUTORVAILD);
        return Convert.ToBoolean(str != string.Empty ? str : false);
    }

    /// <summary>
    /// 刷新获取票据
    /// </summary>
    /// <returns></returns>
    private JsonData RefreshWxSession()
    {
        var jsonData = JsonMapper.ToObject(PlatformMsgManager.Instance.GetStringFormPlatform(Constants.UNITY_GET_STRING_WX_REFRESHSESSION));

        return jsonData;
    }
}

public enum PlatformEnum
{
    None,
    QQ = 1,
    WX = 2
}
